package lesson30;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class MyNIO {

    static volatile boolean stop = false;

    public static void main(String[] args) throws IOException {

        int count = 0;

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress("localhost", 9000));

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, serverSocketChannel.validOps());

        while (!stop){
            if(count >= 10){
                stop = true;
            }
            int num = selector.select();
            if(num <= 0){
                continue;
            }
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if(selectionKey.isAcceptable()){
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    count ++;
                } else if(selectionKey.isReadable()){
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int size = socketChannel.read(byteBuffer);
                    if(size == -1){
                        System.out.println("size : " +size);
                        socketChannel.close();
                    }else{
                        System.out.println("size : " +size);
                    }
                    String result = new String(byteBuffer.array()).trim();
                    ByteBuffer wrap = ByteBuffer.wrap(("PONG : " + result).getBytes());
                    socketChannel.write(wrap);
                }else if(selectionKey.isWritable()){
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                }
                iterator.remove();
            }

        }
    }
}
